//
//  BeautyTableViewController.swift
//  4-5classWork
//
//  Created by Qingke on 16/4/6.
//  Copyright © 2016年 Qingke. All rights reserved.
//

import UIKit

class BeautyTableViewController:UITableViewController {
    var mms = [Beauty]()
    override func viewDidLoad() {
        super.viewDidLoad()
        navigationItem.leftBarButtonItem = editButtonItem()
        navigationItem.leftBarButtonItem?.title = "编辑"
        if let loadmms = loadDate(){
            mms = loadmms
        }
        
       
        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return mms.count
    }

    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("beautyCell", forIndexPath: indexPath) as! BeautyTableViewCell
       
        let m = mms[indexPath.row]
        cell.photo.image = m.photo
        cell.nameLabel.text = m.name
        cell.rating.rating = Int(m.ranting)
        return cell
    }

    @IBAction func unWindFOrSegueList (segue:UIStoryboardSegue ) {
        if let sourceViewController = segue.sourceViewController as? ViewController , beauty = sourceViewController.beauty {
            
            if let selectIndexOfCell = tableView.indexPathForSelectedRow {
                mms [selectIndexOfCell.row] = beauty
                tableView.reloadRowsAtIndexPaths([selectIndexOfCell], withRowAnimation: .None)
            } else {
                let newIndexPath = NSIndexPath(forRow: mms.count, inSection: 0)
                mms.append(beauty)
                tableView.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: .Bottom)
            }
        }
        saveDate()
        
    }

    override func setEditing(editing: Bool, animated: Bool) {
       super.setEditing(editing, animated: animated)
        if editing {
            navigationItem.leftBarButtonItem?.title = "完成 "
        } else {
            navigationItem.leftBarButtonItem?.title = "编辑"
        }
    }

    
    // Override to support conditional editing of the table view.
    override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return true
    }


    
    // Override to support editing the table view.
    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if editingStyle == .Delete {
            mms.removeAtIndex(indexPath.row)
            
            tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
        } else if editingStyle == .Insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }


    func saveDate(){
        let isSaveSuccess = NSKeyedArchiver.archiveRootObject( mms, toFile: Beauty.ArchiveURl.path!)
        if !isSaveSuccess {
            print("保存失败")
        } else {
            print("保存成功")
        }
    }
    
    func loadDate() ->[Beauty]? {
        return NSKeyedUnarchiver.unarchiveObjectWithFile(Beauty.ArchiveURl.path!) as? [Beauty]
    }
    
    func basicDate() {
        let mm1 = Beauty(name: "美女1", photo: UIImage(named: "mm1"), ranting: 4)
        let mm2 = Beauty(name: "美女2", photo: UIImage(named: "mm2"), ranting: 3)
        let mm3 = Beauty(name: "美女3", photo: UIImage(named: "mm3"), ranting: 2)
        mms = [mm1!,mm2!,mm3!]
        
    }
    /*
    // Override to support rearranging the table view.
    override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return false if you do not want the item to be re-orderable.
        return true
    }
    */

    
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
        if segue.identifier == "edit" {
            print("准备进入编辑界面")
            //找美女
            let selectedCell = sender as! BeautyTableViewCell
            let indexPath = tableView.indexPathForCell(selectedCell)
            let selectedBeauty = mms[indexPath!.row]
            
            let beautyViewController = segue.destinationViewController as! ViewController
            beautyViewController.beauty = selectedBeauty
        } else {
            print("add")
        }
    }


}
